<template>
   <div style="border: 1px solid #ccc">
      <Toolbar
         style="border-bottom: 1px solid #ccc"
         :editor="editorRef"
         :defaultConfig="toolbarConfig"
         :mode="mode"
      />
      <Editor
         style="height: 500px; overflow-y: hidden"
         v-model="valueHtml"
         :defaultConfig="editorConfig"
         :mode="mode"
         @onCreated="handleCreated"
         @onChange="handleChange"
         @onDestroyed="handleDestroyed"
         @onFocus="handleFocus"
         @onBlur="handleBlur"
         @customAlert="customAlert"
         @customPaste="customPaste"
      />
   </div>
</template>
<script>
   import "@wangeditor/editor/dist/css/style.css"; // 引入 css

   import { onBeforeUnmount, ref, shallowRef, onMounted, watch, computed } from "vue";
   import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
   import { usePublicDataStore } from "@/stores/publicData"; // 导入 store
   import { ElMessage } from "element-plus";
   import { Plus } from "@element-plus/icons-vue";
   import { fi } from "element-plus/es/locales.mjs";

   export default {
      components: { Editor, Toolbar, Plus },
      props: {
         modelValue: {
            type: String,
            default: "",
         },
         height: {
            type: String,
            default: "500px",
         },
         uploadPath: {
            type: String,
            default: "/api/upload",
         },
         imageLimit: {
            type: Number,
            default: 5,
         },
         videoLimit: {
            type: Number,
            default: 10,
         },
      },
      emits: ["update:modelValue", "change"],
      setup(props, { emit }) {
         // 获取public store
         const publicDataStore = usePublicDataStore();

         // 编辑器实例，必须用 shallowRef
         const editorRef = shallowRef();

         // 内容 HTML
         const valueHtml = ref(props.modelValue || "<p></p>");

         // 上传地址
         const uploadUrl = computed(() => {
            return publicDataStore.baseURL.split("/admin")[0] + props.uploadPath;
         });

         // 文件验证
         const beforeImageUpload = (file) => {
            let keys = Object.keys(file);
            console.log("上传文件类型:", file[keys].type);
            // console.log("上传文件类型:", file.keys[0]);
            const isImage = ["image/jpeg", "image/png", "image/gif"].includes( file[keys].type);

            const isLt2M = file.size / 1024 / 1024 < props.imageLimit;

            if (!isImage) {
               console.log("不是图片");
               ElMessage.error(`只能上传JPG/PNG/GIF格式图片!`);
               return false;
            }
            // if (!isLt2M) {
            //    ElMessage.error(`图片大小不能超过${props.imageLimit}MB!`);
            //    return false;
            // }
            return true;
         };

         const beforeVideoUpload = (file) => {
            const isVideo = file.type.startsWith("video/");
            const isLt10M = file.size / 1024 / 1024 < props.videoLimit;

            if (!isVideo) {
               ElMessage.error(`只能上传视频文件!`);
               return false;
            }
            if (!isLt10M) {
               ElMessage.error(`视频大小不能超过${props.videoLimit}MB!`);
               return false;
            }
            return true;
         };

         // 监听 modelValue 变化
         watch(
            () => props.modelValue,
            (newValue) => {
               if (newValue !== valueHtml.value) {
                  valueHtml.value = newValue || "<p></p>";
               }
            }
         );

         // 监听 valueHtml 变化
         watch(valueHtml, (newHtml) => {
            emit("update:modelValue", newHtml);
         });

         const toolbarConfig = {
            excludeKeys: [],
         };

         const editorConfig = {
            placeholder: "请输入内容...",
            MENU_CONF: {
               uploadImage: {
                  server: uploadUrl.value,
                  fieldName: "file",
                  maxFileSize: props.imageLimit * 1024 * 1024,
                  maxNumberOfFiles: 10,
                  allowedFileTypes: ["image/jpeg", "image/png", "image/gif"],
                  meta: {}, // 扩展字段
                  metaWithUrl: true,
                  withCredentials: false, // 跨域请求是否携带 cookie
                  timeout: 10 * 1000, // 超时时间
                  onBeforeUpload(file) {
                     return beforeImageUpload(file);
                  },
                  customInsert(res, insertFn) {
                     // 处理上传结果
                     if (res.code === 0 && res.data) {
                        insertFn(res.data, "图片", res.data);
                        ElMessage.success("图片上传成功");
                     } else {
                        ElMessage.error(res.msg || "图片上传失败");
                     }
                  },
                  onError(file, err, res) {
                     console.error("图片上传失败", file, err, res);
                     ElMessage.error("图片上传失败");
                  },
               },
               uploadVideo: {
                  server: uploadUrl.value,
                  fieldName: "file",
                  maxFileSize: props.videoLimit * 1024 * 1024,
                  maxNumberOfFiles: 5,
                  allowedFileTypes: ["video/mp4", "video/quicktime"],
                  meta: {}, // 扩展字段
                  metaWithUrl: true,
                  withCredentials: false, // 跨域请求是否携带 cookie
                  timeout: 30 * 1000, // 超时时间
                  onBeforeUpload(file) {
                     return beforeVideoUpload(file);
                  },
                  customInsert(res, insertFn) {
                     // 处理上传结果
                     if (res.code === 0 && res.data) {
                        insertFn(res.data);
                        ElMessage.success("视频上传成功");
                     } else {
                        ElMessage.error(res.msg || "视频上传失败");
                     }
                  },
                  onError(file, err, res) {
                     console.error("视频上传失败", file, err, res);
                     ElMessage.error("视频上传失败");
                  },
               },
            },
         };

         // 组件销毁时，也及时销毁编辑器
         onBeforeUnmount(() => {
            const editor = editorRef.value;
            if (editor == null) return;
            editor.destroy();
         });

         const handleCreated = (editor) => {
            editorRef.value = editor; // 记录 editor 实例，重要！
         };

         const handleChange = (editor) => {
            emit("change", editor.getHtml());
         };

         const handleDestroyed = (editor) => {
            console.log("destroyed", editor);
         };

         const handleFocus = (editor) => {
            console.log("focus", editor);
         };

         const handleBlur = (editor) => {
            console.log("blur", editor);
         };

         const customAlert = (info, type) => {
            console.log(`编辑器提示: ${type} - ${info}`);
         };

         const customPaste = (editor, event, callback) => {
            // 默认行为
            callback(true);
         };

         return {
            editorRef,
            valueHtml,
            mode: "default", // 或 'simple'
            toolbarConfig,
            editorConfig,
            handleCreated,
            handleChange,
            handleDestroyed,
            handleFocus,
            handleBlur,
            customAlert,
            customPaste,
         };
      },
   };
</script>

<style scoped>
   .w-e-text-container {
      height: auto !important;
      min-height: 300px !important;
   }

   :deep(.w-e-toolbar) {
      border-top-left-radius: 4px;
      border-top-right-radius: 4px;
   }

   :deep(.w-e-text-container) {
      border-bottom-left-radius: 4px;
      border-bottom-right-radius: 4px;
   }
</style>
